package com.weareint.common.advices;

import com.alibaba.fastjson.JSONObject;
import com.weareint.common.exceptions.UnAuthenticationException;
import com.weareint.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * <pre>
 *     在进入Controller层之前发生的异常，比如参数校验
 * </pre>
 *
 */
@Slf4j
@ControllerAdvice
public class RaiseExceptionBeforeControllerHandler {

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<Void> BindExceptionHandler(BindException e) {
        return internalExceptionHandler(e.getBindingResult());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result<Void> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            violation.getPropertyPath();
            violation.getMessage();
        }
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return Result.error(message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<Void> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        return internalExceptionHandler(e.getBindingResult());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Void> exceptionHandler(Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
        }
        if (e instanceof DuplicateKeyException){
            return Result.error("数据库唯一性约束失败");
        }
        String message = e.getMessage();
        return Result.error("服务器内部异常["+ message +"]");
    }

    @ExceptionHandler(UnAuthenticationException.class)
    @ResponseBody
    public Result<Void> unAuthenticationExecptionHanlder(UnAuthenticationException e) {
        if (log.isErrorEnabled()) {
            log.error(e.getMessage(), e);
        }
        String message = e.getMessage();
        return Result.unauth(message);
    }

    private Result<Void> internalExceptionHandler(BindingResult bindingResult) {
        String msg = null;
        List<FieldError> errors = bindingResult.getFieldErrors();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError error : errors) {
            String fieldName = error.getField();
            String errorMessage = error.getDefaultMessage();
            errorMap.put(fieldName, errorMessage);
            if (msg == null) {
                msg = errorMessage;
            }
        }
        return Result.error(JSONObject.toJSONString(errorMap));
    }
}
